import { INestApplication, Logger, LoggerService, ValidationPipe } from '@nestjs/common'
import { HttpExceptionFilter } from './filters/http-exception.filter'
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston'
import { HttpAdapterHost } from '@nestjs/core'
import { AllExceptionFilter } from './filters/all-exception.filter'
import { getServicerConfig } from '../ormconfig'

export const setupApp = (app: INestApplication, logger?: LoggerService) => {
  //根据配置文件中是否启用了日志功能（LOG_ON）来决定是否启用日志记录功能
  const config = getServicerConfig()
  const flag: boolean = config['LOG_ON'] === 'true'
  //   app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER))
  if (flag) {
    app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER))
  }
  // 全局的filter只能有一个
  app.useGlobalFilters(new HttpExceptionFilter(Logger))
  const httpAdapter = app.get<HttpAdapterHost>(HttpAdapterHost)
  if (logger) {
    app.useGlobalFilters(new AllExceptionFilter(logger, httpAdapter))
  }
  // 全局管道
  app.useGlobalPipes(
    new ValidationPipe({
      // 去除在类上不存在的字段
      whitelist: true,
      exceptionFactory: (errors) => {
        return {
          code: 400,
          message: errors.map((err) => err.constraints)
        }
      }
    })
  )
  // 全局拦截器
  // app.useGlobalInterceptors(new SerializeInterceptor())
  // app.setGlobalPrefix() 方法设置一个全局的路由前缀，所有路由路径都会自动添加该前缀。这通常用于 API 的版本控制和路由结构管理。
  app.setGlobalPrefix('api/v1')
}
